#include "retransmission.h"

uint8_t retransmission_usart_rx_buffer[10];
uint8_t retransmission_can_rx_buffer[8];
uint8_t retransmission_usart_tx_buffer[20] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F,
																						0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

void retransmission_usart_init()
{
	__HAL_UART_ENABLE_IT(&huart1, UART_IT_RXNE);
	__HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);
	HAL_UART_Receive_DMA(&huart1, retransmission_usart_rx_buffer, 10);
}

void retransmission_can_init()
{
	CAN_FilterTypeDef filter;
	filter.FilterBank=1;
	filter.FilterMode=CAN_FILTERMODE_IDMASK;
	filter.FilterScale=CAN_FILTERSCALE_16BIT;
	filter.FilterIdHigh=0x000;
	filter.FilterIdLow=0x0000;
	filter.FilterMaskIdHigh=0x0000;
	filter.FilterMaskIdLow=0x0000;
	filter.FilterFIFOAssignment=CAN_FILTER_FIFO0;
	filter.FilterActivation=ENABLE;
	
	HAL_CAN_ConfigFilter(&hcan, &filter);
	HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING);
	HAL_CAN_Start(&hcan);
}

void retransmission_usart_to_can(uint8_t length)
{
	uint16_t std_id = retransmission_usart_rx_buffer[1] | (retransmission_usart_rx_buffer[0] << 8);
	uint32_t CAN_TX_BOX0;
	CAN_TxHeaderTypeDef tx_header;
	tx_header.StdId = std_id;
	tx_header.IDE = CAN_ID_STD;
	tx_header.RTR = CAN_RTR_DATA;
	tx_header.DLC = length;
	tx_header.TransmitGlobalTime = DISABLE;
	HAL_CAN_AddTxMessage(&hcan, &tx_header, retransmission_usart_rx_buffer + 2, &CAN_TX_BOX0);
	HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_6);
}

void retransmission_can_to_usart(uint16_t std_id, uint8_t length)
{
	retransmission_usart_tx_buffer[9] = 0x0F | length << 4;
	retransmission_usart_tx_buffer[10] = std_id >> 8;
	retransmission_usart_tx_buffer[11] = std_id;
	HAL_UART_Transmit_DMA(&huart1, retransmission_usart_tx_buffer, 20);
	HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_6);
}

void retransmission_usart_callback()
{
	if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET)
	{
		__HAL_UART_CLEAR_IDLEFLAG(&huart1);
		HAL_UART_AbortReceive(&huart1);
		//HAL_UART_DMAStop(&huart1);
		extern DMA_HandleTypeDef hdma_usart1_rx;
		uint8_t buffer_number = __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);
		if (buffer_number <= 8)
		{
			uint8_t length = 8 - buffer_number;
			retransmission_usart_to_can(length);
		}
		HAL_UART_Receive_DMA(&huart1, retransmission_usart_rx_buffer, 10);
	}
}

void retransmission_can_callback()
{
	CAN_RxHeaderTypeDef rx_header;
	HAL_CAN_GetRxMessage(&hcan, CAN_RX_FIFO0, &rx_header, retransmission_usart_tx_buffer + 12);
	retransmission_can_to_usart(rx_header.StdId, rx_header.DLC);
}
